//
//  MainVC.m
//  BasketballTool
//
//  Created by 饶首建 on 17/3/23.
//  Copyright © 2017年 com.vince.rao. All rights reserved.
//

#import "MainVC.h"

#import "HWPopTool.h"
#import "ControlButton.h"
#import "MahjongTypeCollectionViewCell.h"
#import "MahjongRecordCell.h"
#import "ResultTableViewCell.h"
#import "ChartHeaderView.h"

#import "PatternModel.h"
#import "GameModel.h"
#import "ResultModel.h"
#import "ActionModel.h"

#import "Mahjong-swift.h"

@interface MainVC () <GameCallBackDelegate,UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property (weak, nonatomic) IBOutlet UIView *chartView;
@property (weak, nonatomic) IBOutlet UIButton *backBtn;
@property (weak, nonatomic) IBOutlet UIButton *createGameBtn;
@property (weak, nonatomic) IBOutlet UILabel *ruleLabel;
@property (weak, nonatomic) IBOutlet UIButton *netStatusBtn;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic,strong) dispatch_source_t timer;

@property (nonatomic,strong) ChartHeaderView *chartHeaderView;

@property (nonatomic,strong) UITableView *controlTableView;
@property (nonatomic,strong) UITableView *resultTableView;
@property (nonatomic,strong) NSMutableArray *resultActionArr;

@property (nonatomic,assign) CGFloat scrollViewW;
@property (nonatomic,assign) CGFloat scrollViewH;

@property (nonatomic,strong) UICollectionView *collectionView;

@property (nonatomic,strong) UILabel *tipLabel;

//存储数据
@property (nonatomic,strong) NSMutableArray *gameArr;
@property (nonatomic,strong) NSArray *selectedRuleArr;

@property (nonatomic,strong) PatternModel *patternModel;
@property (nonatomic,strong) GameModel *currentGameModel;
@property (nonatomic,strong) PlayerModel *owner;

@property (nonatomic,strong) NSArray *typeNameArr;

@property (nonatomic,copy) NSString *selectedActionName;
@property (nonatomic,copy) NSString *selectedGangeName;
@property (nonatomic,strong) NSMutableArray *selectedAttributeNameArr;
@property (nonatomic,strong) NSMutableArray *selectedTargetPlayerArr;
@property (nonatomic,assign) BOOL isEditAction;
@property (nonatomic,strong) ActionModel *selectedTagAction;
@property (nonatomic,strong) NSArray *leftPlayerArr;//未胡牌的玩家

@property (nonatomic,strong) UIButton *selectedBtn;//胡、杠、查叫
@property (nonatomic,strong) UIButton *selectedGangBtn;//
@property (nonatomic,copy) NSString *selectedGangType;//下雨、刮风、直杠

@end

static NSString *kMahjongRecordCell = @"kMahjongRecordCell";
static NSString *kMahjongTypeCollectionViewCell = @"kMahjongTypeCollectionViewCell";
static NSString *kResultTableViewCell = @"ResultTableViewCell";

@implementation MainVC

- (void)loadGames{
    [GameModel gamesOfMatch:_matchModel.matchId success:^(id array) {
        [self.tableView.mj_header endRefreshing];
        
        [_gameArr removeAllObjects];
        NSMutableArray *tmp = [NSMutableArray arrayWithArray:array];
        tmp = (NSMutableArray *)[[tmp reverseObjectEnumerator] allObjects];
        [_gameArr addObjectsFromArray:tmp];
        
        [self updateChart];
        if (_gameArr.count) {
            _tipLabel.hidden = YES;
        }
        
        [_tableView reloadData];
    } fail:^(NSString *errorStr) {
        [self.tableView.mj_header endRefreshing];
        [Hud hudText:errorStr inView:self.view];
    }];
}

- (void)newGame{
    NSString *url = [BASE_URL stringByAppendingPathComponent:NSStringFormat(@"Matches/%@/games",_matchModel.matchId)];
    NSDictionary *param = @{};
    [HttpUtil sendRequestURL:url method:POST param:param success:^(id response) {
    } fail:^(NSString *errorStr) {
        [Hud hudText:errorStr inView:self.view];
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initData];
    [self initUI];
    [self socketConnet];
//    [self createTimer];
    
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadGames];
    }];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(becameActive) name:@"reloadGames" object:nil];
}

- (void)becameActive{
    [self loadGames];
}

- (void)socketConnet{
    WebSocketUtil *socketUtil = [WebSocketUtil sharedInstance];
    [socketUtil connect:@{@"matchId":_matchModel.matchId,@"playerName":_matchModel.me.playerName}];
    socketUtil.delegate = self;
}

- (void)initData{
    //加载pattern
    [PatternModel loadPatternDataSuccess:^(id model) {
        _patternModel = model;
    } fail:^(NSString *errorStr) {}];
    
    _owner = _matchModel.me;
    _selectedRuleArr = _matchModel.rules;
    _gameArr = [NSMutableArray new];
    _scrollViewW = SWidth() * 4/5;//modal 宽度
    _scrollViewH = SHeight() * 4/5;//modal 高度
    
    _selectedAttributeNameArr = [NSMutableArray new];
    _selectedTargetPlayerArr = [NSMutableArray new];
}

- (void)initUI{
    //tipLabel
    _tipLabel = self.tipLabel;
    [self.view addSubview:_tipLabel];
    [self setTipLabelText:_matchModel.players];
    
    //退出按钮
    _backBtn.layer.cornerRadius = 25;
    _backBtn.layer.masksToBounds = YES;
    _backBtn.backgroundColor = [UIColor colorWithRed:00 green:00 blue:00 alpha:0.3];
    //网络状态
//    _netStatusBtn.backgroundColor = [UIColor colorWithRed:00 green:00 blue:00 alpha:0.3];
    //已选规则
    if (_matchModel.rules.count > 0) {
        _ruleLabel.backgroundColor = [UIColor colorWithRed:00 green:00 blue:00 alpha:0.3];
        _ruleLabel.text = NSStringFormat(@"已选规则:%@",[_matchModel.rules componentsJoinedByString:@","]);
        _ruleLabel.hidden = NO;
    }else{
        _ruleLabel.hidden = YES;
    }
    //新建游戏
    _createGameBtn.layer.cornerRadius = 25;
    _createGameBtn.layer.masksToBounds = YES;
    _createGameBtn.backgroundColor = [UIColor colorWithRed:00 green:00 blue:00 alpha:0.3];
    //图表
    [self initChart];
    //tableView
    [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([MahjongRecordCell class]) bundle:nil] forCellReuseIdentifier:kMahjongRecordCell];
    [_tableView reloadData];
}

#pragma mark - 图表
- (void)initChart{
    _chartHeaderView = [[ChartHeaderView alloc]initWithFrame:CGRectMake(20, 20, _tableView.frame.size.width, 380) gameArr:_gameArr matchModel:_matchModel];
    _tableView.tableHeaderView = _chartHeaderView;
}

- (void)updateChart{
    [_chartHeaderView updateChartGameArr:_gameArr matchModel:_matchModel];
}

#pragma mark - 退出
- (IBAction)backAction:(id)sender {
    [UIAlertView showWithTitle:@"警告" message:@"确定要退出？" cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] tapBlock:^(UIAlertView * _Nonnull alertView, NSInteger buttonIndex) {
        if (buttonIndex == 1) {
            [self dismissViewControllerAnimated:YES completion:^{
                [[WebSocketUtil sharedInstance]close];
            }];
        }
    }];
}

#pragma mark - 新局
- (IBAction)createGameAction:(id)sender {
    [self newGame];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == _tableView) {
        return _gameArr.count;
    }else if (tableView == _resultTableView){
        return _resultActionArr.count;
    }
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _controlTableView) {
        UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"controlTableViewID"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (indexPath.row == 0) {
            [self loadTypeCell:cell];
        }else if (indexPath.row == 1){
            [self loadNaviCell:cell];
        }else if (indexPath.row == 2){
            if ([_selectedBtn.titleLabel.text isEqualToString:@"杠"]){
                //杠
                [self loadGangCell:cell];
            }else if([_selectedBtn.titleLabel.text isEqualToString:@"胡"]){
                //胡
                _typeNameArr = _patternModel.huPatternArr;
                [self loadAttributeCell:cell];
            }else{
                //查
                _typeNameArr = _patternModel.chaPatternArr;
                [self loadAttributeCell:cell];
            }
        }else if (indexPath.row == 3){
            [self loadPlayerCell:cell];
        }
        return cell;
    }else if (tableView == _resultTableView){
        ResultTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kResultTableViewCell forIndexPath:indexPath];
        cell.owner = _owner;
        cell.cellIdx = indexPath.row;
        cell.resultActionArr = _resultActionArr;
        cell.actionModel = _resultActionArr[indexPath.row];
        return cell;
    }
#pragma mark - 牌局记录
    MahjongRecordCell *cell = [tableView dequeueReusableCellWithIdentifier:kMahjongRecordCell forIndexPath:indexPath];
    cell.indexLabel.text = NSStringFormat(@"第%ld局",_gameArr.count-indexPath.row);
    if (indexPath.row > 0) {
        cell.recordBtn.backgroundColor = [UIColor lightGrayColor];
        cell.resultBtn.backgroundColor = [UIColor lightGrayColor];
    }else{
        cell.recordBtn.backgroundColor = UIColorHex(#EE8222);
        cell.resultBtn.backgroundColor = UIColorHex(#8BB335);
    }
    if (indexPath.row%2 == 0) {
        cell.contentView.backgroundColor = UIColorHex(#F7F7F7);
    }else{
        cell.contentView.backgroundColor = UIColorHex(#EEEEEE);
    }
    cell.owner = _owner;
    GameModel *gm = _gameArr[indexPath.row];
    cell.gameModel = gm;
#pragma mark - 记录Action
    cell.recordBlock = ^(){
        _isEditAction = NO;
        _currentGameModel = _gameArr[indexPath.row];
        [self leftPlayers];
        [self resetSelectedData];
        
        
        [self showModalWithView:self.controlTableView];
        [_controlTableView scrollToRow:0 inSection:0 atScrollPosition:UITableViewScrollPositionTop animated:YES];
    };
#pragma mark - 标签Action
    cell.tagClickBlock = ^(id data){
        _isEditAction = YES;
        _selectedTagAction = data;
        _currentGameModel = _gameArr[indexPath.row];
        [self leftPlayers];
        [self resetSelectedData];
        
        ActionModel *am = data;
        _selectedActionName = am.actionType;
        [_selectedAttributeNameArr addObjectsFromArray:am.attributesArr];
        [_selectedTargetPlayerArr addObjectsFromArray:am.targetsArr];

        [self showModalWithView:self.controlTableView];
        [_controlTableView scrollToRow:2 inSection:0 atScrollPosition:UITableViewScrollPositionTop animated:YES];
    };
#pragma mark - 流水Action
    cell.detailBlock = ^(){
        _currentGameModel = _gameArr[indexPath.row];
        [self detailActionResult];
    };
    return cell;
}

#pragma mark UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _typeNameArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MahjongTypeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kMahjongTypeCollectionViewCell forIndexPath:indexPath];
    
    NSString *title = _typeNameArr[indexPath.row];
    cell.titleLabel.text = title;
    cell.titleLabel.textColor = [UIColor grayColor];
    
    if ([_selectedAttributeNameArr containsObject:title]) {
        cell.titleLabel.backgroundColor = [UIColor redColor];
        cell.titleLabel.textColor = [UIColor whiteColor];
    }else{
        cell.titleLabel.backgroundColor = UIColorHex(EAEAEA);
        cell.titleLabel.textColor = [UIColor grayColor];
    }
    
    return cell;
}

#pragma mark - 杠、胡、查
- (void)loadTypeCell:(UITableViewCell*)cell{
    CGFloat w = 200;
    CGFloat y = (_scrollViewH - w)/2;
    CGFloat margin = (_scrollViewW - 3*200)/4;
    NSArray *actionArry = @[@"杠",@"胡",@"查叫"];
    for (int i=0; i<actionArry.count; i++) {
        ControlButton *btn = [[ControlButton alloc]initWithTitle:actionArry[i] fontSize:44 cornerRadius:w/2];
        btn.frame = CGRectMake((i+1)*margin + i*w, y, w, w);
        [cell.contentView addSubview:btn];
        [btn addTapBlock:^(UIButton *_btn) {
            [self typeTap:_btn];
        }];
        //未选状态
        [self setButtonStatus:btn selected:NO];
        
        if (_isEditAction) {
            if ([actionArry[i] isEqualToString:_selectedActionName]) {
                _selectedBtn = btn;
                [self setButtonStatus:btn selected:YES];
            }
        }
    }
    
}

- (void)typeTap:(UIButton*)btn{
    _selectedBtn = btn;
    _selectedActionName = btn.titleLabel.text;
    
    if (![btn.titleLabel.text isEqualToString:@"杠"]) {
        _selectedGangBtn = nil;
    }
    if ([btn.titleLabel.text isEqualToString:@"胡"]) {
        _typeNameArr = _patternModel.huPatternArr;
    }else if ([btn.titleLabel.text isEqualToString:@"查叫"]) {
        _typeNameArr = _patternModel.chaPatternArr;
    }
    
    for (ControlButton *button in btn.superview.subviews) {
        [self setButtonStatus:button selected:NO];
    }
    [self setButtonStatus:btn selected:YES];
    
    if (!_isEditAction) {
        [_selectedTargetPlayerArr removeAllObjects];
        [_selectedAttributeNameArr removeAllObjects];
    }
    
    [_collectionView reloadData];
    [_controlTableView scrollToRow:2 inSection:0 atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

#pragma mark - Navi操作（返回、确定）
- (void)loadNaviCell:(UITableViewCell*)cell{
    ControlButton *backBtn = [[ControlButton alloc]initWithTitle:@"返回" fontSize:23];
    backBtn.frame = CGRectMake(20, 10, 100, 60);
    [cell.contentView addSubview:backBtn];
    //返回
    [backBtn addTapBlock:^(UIButton *btn) {
        [_controlTableView scrollToRow:0 inSection:0 atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }];
    
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake((_scrollViewW - 200)/2, 25, 200, 30)];
    titleLabel.text = _selectedBtn.titleLabel.text;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = DefaultSystemFont(23);
    titleLabel.textColor = [UIColor grayColor];
    [cell.contentView addSubview:titleLabel];
    
    ControlButton *sureBtn = [[ControlButton alloc]initWithTitle:@"确定" fontSize:23];
    sureBtn.frame = CGRectMake(_scrollViewW - 140, 10, 100, 60);
    [cell.contentView addSubview:sureBtn];
    //确定
    [sureBtn addTapBlock:^(UIButton *btn) {
        [self sendAction];
    }];
    
    if (_isEditAction) {
        ControlButton *delBtn = [[ControlButton alloc]initWithTitle:@"删除" fontSize:23];
        delBtn.layer.borderColor = [UIColor redColor].CGColor;
        [delBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        delBtn.frame = CGRectMake(_scrollViewW - 140 - 120, 10, 100, 60);
        [cell.contentView addSubview:delBtn];
        //删除按钮
        [delBtn addTapBlock:^(UIButton *btn) {
            [ActionModel deleteActionByGameId:_currentGameModel.gameId actionId:_selectedTagAction.actionId success:^(id model) {
                [[HWPopTool sharedInstance] closeWithBlcok:^{}];
            } fail:^(NSString *errorStr) {
                [Hud hudText:errorStr inView:self.view];
                [[HWPopTool sharedInstance] closeWithBlcok:^{}];
            }];
        }];
    }
}

#pragma mark - 发送Action
- (void)sendAction{
    if (_selectedTargetPlayerArr.count ==0) {
        [Hud hudText:@"请选择玩家" inView:[self getCurrentVC].view];
        return;
    }
    NSString *url = NSStringFormat(@"%@/Games/%@/actions",BASE_URL,_currentGameModel.gameId);
    NSMutableArray *tmp = [NSMutableArray new];
    for (PlayerModel *pm in _selectedTargetPlayerArr) {
        [tmp addObject:@{
                         @"id":pm.playerId,
                         @"name":pm.playerName
                         }];
    }

    NSDictionary *param = @{
                            @"type":_selectedBtn.titleLabel.text,
                            @"attributes":_selectedAttributeNameArr,
                            @"owner":@{
                                        @"id":_owner.playerId,
                                        @"name":_owner.playerName
                                    },
                            @"targets":tmp
                            };
    if (_isEditAction) {
        [ActionModel putActionByGameId:_currentGameModel.gameId actionId:_selectedTagAction.actionId param:param success:^(id model) {
            [[HWPopTool sharedInstance] closeWithBlcok:^{}];
        } fail:^(NSString *errorStr) {
            [Hud hudText:errorStr inView:self.view];
            [[HWPopTool sharedInstance] closeWithBlcok:^{}];
        }];
    }else{
        [HttpUtil sendRequestURL:url method:POST param:param success:^(id response) {
            [[HWPopTool sharedInstance] closeWithBlcok:^{}];
        } fail:^(NSString *errorStr) {
            [Hud hudText:errorStr inView:self.view];
            [[HWPopTool sharedInstance] closeWithBlcok:^{}];
        }];
    }
}

#pragma mark - 麻将属性 - 选择
- (void)loadAttributeCell:(UITableViewCell*)cell{
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
        flowLayout.minimumLineSpacing = 0;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, _scrollViewW, _scrollViewH - 60 - 160) collectionViewLayout:flowLayout];
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.contentInset = UIEdgeInsetsMake(10, 10, 10, 10);
        [_collectionView registerClass:[MahjongTypeCollectionViewCell class] forCellWithReuseIdentifier:kMahjongTypeCollectionViewCell];
    }
    [cell.contentView addSubview:_collectionView];
}

#pragma mark - 杠操作
- (void)loadGangCell:(UITableViewCell*)cell{
    CGFloat margin = 40;
    CGFloat w = (_scrollViewW - 4*margin)/3;
    CGFloat h = 100;
    CGFloat y = (_scrollViewH - 100 - 160 - h)/2;
    
    for (int i=0; i<_patternModel.gangPatternArr.count; i++) {
        ControlButton *btn = [[ControlButton alloc]initWithTitle:_patternModel.gangPatternArr[i] fontSize:30 bgColor:UIColorHex(EAEAEA)];
        btn.frame = CGRectMake((i+1)*margin + i*w, y, w, h);
        [cell.contentView addSubview:btn];
        [btn addTapBlock:^(UIButton *btn) {
            [self gangTap:cell btn:btn];
        }];
        
        if (_isEditAction && [_patternModel.gangPatternArr[i] isEqualToString:[_selectedAttributeNameArr firstObject]]) {
            btn.backgroundColor = [UIColor redColor];
            [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        }
    }
}

- (void)gangTap:(UITableViewCell*)cell btn:(UIButton*)btn{
    _selectedGangBtn = btn;
    
    for (UIView *v in cell.contentView.subviews) {
        if ([v isKindOfClass:[ControlButton class]]) {
            v.backgroundColor = UIColorHex(EAEAEA);
            UIButton *b = (UIButton*)v;
            [b setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        }
    }
    [_selectedAttributeNameArr removeAllObjects];
    [_selectedAttributeNameArr addObject:btn.titleLabel.text];
    btn.backgroundColor = [UIColor redColor];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [_selectedTargetPlayerArr removeAllObjects];
    if ([_selectedAttributeNameArr containsObject:@"暗杠"]||[_selectedAttributeNameArr containsObject:@"补杠"]) {
        if ([_selectedRuleArr containsObject:@"血流成河"]) {
            [_selectedTargetPlayerArr addObjectsFromArray:_matchModel.others];
        }else{
            [_selectedTargetPlayerArr addObjectsFromArray:_leftPlayerArr];
        }
    }else{
        if ([_selectedRuleArr containsObject:@"血流成河"]) {
            [_selectedTargetPlayerArr addObject:_matchModel.others.firstObject];
        }else{
            if (_leftPlayerArr.count) {
                [_selectedTargetPlayerArr addObject:_leftPlayerArr.firstObject];
            }
        }
    }
    [_controlTableView reloadRow:3 inSection:0 withRowAnimation:UITableViewRowAnimationNone];
}
#pragma mark - 玩家选择
- (void)loadPlayerCell:(UITableViewCell*)cell{
    CGFloat w = 140;
    CGFloat y = 10;
    CGFloat margin = (_scrollViewW - 3*w)/4;
    
    NSMutableArray *selectedPlayerIdArr = [NSMutableArray new];
    for (PlayerModel *pm in _selectedTargetPlayerArr) {
        [selectedPlayerIdArr addObject:pm.playerId];
    }
    
    //已胡玩家
    NSMutableArray *gonePlayerIdArr = [NSMutableArray new];
    for (ActionModel *am in _currentGameModel.actionArr) {
        if ([am.actionType isEqualToString:@"胡"]) {
            [gonePlayerIdArr addObject:am.owner.playerId];
        }
    }
    
    for (int i=0 ; i<_matchModel.others.count ; i++) {
        PlayerModel *pm = _matchModel.others[i];
        ControlButton *btn = [[ControlButton alloc]initWithTitle:pm.playerName fontSize:34 cornerRadius:w/2];
        btn.frame = CGRectMake((i+1)*margin+i*w, y, w, w);
        [cell.contentView addSubview:btn];
        
        if ([selectedPlayerIdArr containsObject:pm.playerId]) {
            btn.layer.borderColor = [UIColor redColor].CGColor;
            [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            btn.layer.borderWidth = 0;
            [btn setBackgroundImage:UIImageWithName(@"player_selected") forState:UIControlStateNormal];
            
            [btn addTapBlock:^(UIButton *btn) {
                [self playerTap:cell btn:btn];
            }];
        }else{
            if (![_selectedRuleArr containsObject:@"血流成河"] && [gonePlayerIdArr containsObject:pm.playerId]) {
                btn.layer.borderColor = [UIColor grayColor].CGColor;
                [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
                btn.layer.borderWidth = 0;
                [btn setBackgroundImage:UIImageWithName(@"playerWin") forState:UIControlStateNormal];
            }else{
                btn.layer.borderColor = [UIColor grayColor].CGColor;
                [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
                btn.layer.borderWidth = 0;
                [btn setBackgroundImage:UIImageWithName(@"player_unSelect") forState:UIControlStateNormal];
                
                [btn addTapBlock:^(UIButton *btn) {
                    [self playerTap:cell btn:btn];
                }];
            }
        }
    }
}

- (void)playerTap:(UITableViewCell*)cell btn:(UIButton*)btn{
    //点击的玩家
    PlayerModel *pm;
    for (PlayerModel *p in _matchModel.players) {
        if ([p.playerName isEqualToString:btn.titleLabel.text]) {
            pm = p;
            break;
        }
    }
    
    NSMutableArray *tmpPlayerIdArr = [NSMutableArray new];
    for (PlayerModel *pm in _selectedTargetPlayerArr) {
        [tmpPlayerIdArr addObject:pm.playerId];
    }
    
    if ([tmpPlayerIdArr containsObject:pm.playerId]) {
        for (PlayerModel *p in _selectedTargetPlayerArr) {
            if ([p.playerId isEqualToString:pm.playerId]) {
                [_selectedTargetPlayerArr removeObject:p];
                break;
            }
        }
        btn.layer.borderColor = [UIColor grayColor].CGColor;
        [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        btn.layer.borderWidth = 0;
        [btn setBackgroundImage:UIImageWithName(@"player_unSelect") forState:UIControlStateNormal];
    }else{
        
        if ([_selectedGangBtn.titleLabel.text isEqualToString:@"直杠"] || (NSNotFound == [_selectedAttributeNameArr indexOfObject:@"杠上花"] && NSNotFound == [_selectedAttributeNameArr indexOfObject:@"自摸"])) {
            if (![_selectedBtn.titleLabel.text isEqualToString:@"查叫"]) {
                [_selectedTargetPlayerArr removeAllObjects];
            }
            [_selectedTargetPlayerArr addObject:pm];
            [_controlTableView reloadRow:3 inSection:0 withRowAnimation:UITableViewRowAnimationNone];
        }else{
            [_selectedTargetPlayerArr addObject:pm];
        }
        
        btn.layer.borderColor = [UIColor redColor].CGColor;
        [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        btn.layer.borderWidth = 0;
        [btn setBackgroundImage:UIImageWithName(@"player_selected") forState:UIControlStateNormal];
    }
}

- (void)leftPlayers{
    //已胡玩家
    NSMutableArray *gonePlayerIdArr = [NSMutableArray new];
    for (ActionModel *am in _currentGameModel.actionArr) {
        if ([am.actionType isEqualToString:@"胡"]) {
            [gonePlayerIdArr addObject:am.owner.playerId];
        }
    }
    //未胡玩家
    NSMutableArray *leftPlayerArr = [NSMutableArray new];
    for (PlayerModel *pm in _matchModel.others) {
        if (![gonePlayerIdArr containsObject:pm.playerId]) {
            [leftPlayerArr addObject:pm];
        }
    }
    _leftPlayerArr = leftPlayerArr;
}

#pragma mark - socket通知:GameCallBackDelegate

- (void)connectCallBack:(id)data{
    Log(@"connectCallBack---------->%@",data);
    [_netStatusBtn setTitle:@"网络正常" forState:UIControlStateNormal];
    [self loadGames];
}

- (void)errorCallBack:(id)data{
    Log(@"errorCallBack---------->%@",data);
    [_netStatusBtn setTitle:@"连接出错" forState:UIControlStateNormal];
}

- (void)disConnectCallBack:(id)data{
    Log(@"disConnectCallBack---------->%@",data);
    [_netStatusBtn setTitle:@"连接已断开" forState:UIControlStateNormal];
}

- (void)newGameCallBack:(id)data{
    Log(@"newGameCallBack----------->%@",data);
    GameModel *mm = [GameModel gameModelPushParse:data];
    [_gameArr insertObject:mm atIndex:0];
    if (_gameArr.count) {
        _tipLabel.hidden = YES;
    }
    [_tableView reloadData];
    [self updateChart];
}

- (void)actionCallBack:(id)data{
    Log(@"actionCallBack----------->%@",data);
    GameModel *returnGameModel = [GameModel gameModelPushParse:data];
    for (int i=0;i<_gameArr.count;i++) {
        GameModel *gm = _gameArr[i];
        if ([returnGameModel.gameId isEqualToString:gm.gameId]) {
            [_gameArr replaceObjectAtIndex:i withObject:returnGameModel];
            [_tableView reloadRow:i inSection:0 withRowAnimation:UITableViewRowAnimationFade];
            break;
        }
    }
    [self updateChart];
}

- (void)matchCallBack:(id)data{
    Log(@"matchCallBack----------->%@",data);
    _matchModel = [MatchModel parseDic:data];
    _matchModel.me = _owner;
    NSMutableArray *othersArr = [NSMutableArray new];
    for (PlayerModel *pm in _matchModel.players) {
        if (![pm.playerId isEqualToString:_owner.playerId]) {
            [othersArr addObject:pm];
        }
    }
    _matchModel.others = othersArr;
    _selectedRuleArr = _matchModel.rules;
    [self updateChart];
    [self setTipLabelText:_matchModel.players];
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    MahjongTypeCollectionViewCell *cell = (MahjongTypeCollectionViewCell*)[collectionView cellForItemAtIndexPath:indexPath];
    NSString *title = cell.titleLabel.text;
    if ([_selectedAttributeNameArr containsObject:title]) {
        [_selectedAttributeNameArr removeObject:title];
    }else{
        [_selectedAttributeNameArr addObject:title];
    }
    
    if ([_selectedAttributeNameArr containsObject:@"自摸"]||[_selectedAttributeNameArr containsObject:@"杠上花"]) {
        [_selectedTargetPlayerArr removeAllObjects];
        if ([_selectedRuleArr containsObject:@"血流成河"]) {
            [_selectedTargetPlayerArr addObjectsFromArray:_matchModel.others];
        }else{
            [_selectedTargetPlayerArr addObjectsFromArray:_leftPlayerArr];
        }
    }else{
        PlayerModel *tmp = _selectedTargetPlayerArr.firstObject;
        [_selectedTargetPlayerArr removeAllObjects];
        if (tmp) {
            [_selectedTargetPlayerArr addObject:tmp];
        }
    }
    
    [_controlTableView reloadRow:3 inSection:0 withRowAnimation:UITableViewRowAnimationNone];
    [_collectionView reloadData];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake((_scrollViewW-90)/5, (_scrollViewW-90)/5*0.6);
}
/**
 *  section的内边距
 */
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(5, 5, 5, 5);
}
/**
 *  section之间的行距
 */
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}
/**
 *  item之间的间距
 */
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 5;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _tableView) {
        return 180.f;
    }else if (tableView == _resultTableView){
        return 60.f;
    }else{
        NSInteger row = indexPath.row;
        switch (row) {
            case 0:
                return _scrollViewH;
                break;
            case 1:
                return 80.f;
                break;
            case 2:
                return _scrollViewH - 80 - 160;
                break;
            case 3:
                return 160.f;
                break;
                
            default:
                break;
        }
        return 0.f;
    }
}

#pragma mark - private method

- (UITableView *)controlTableView{
    if (!_controlTableView) {
        _controlTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, _scrollViewW, _scrollViewH)];
        _controlTableView.delegate = self;
        _controlTableView.dataSource = self;
        _controlTableView.showsVerticalScrollIndicator = NO;
        _controlTableView.scrollEnabled = NO;
    }
    return _controlTableView;
}

- (UITableView *)resultTableView{
    if (!_resultTableView) {
        _resultTableView =  [[UITableView alloc]initWithFrame:CGRectMake(0, 60, _scrollViewW, _scrollViewH - 160)];
        _resultTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _resultTableView.delegate = self;
        _resultTableView.dataSource = self;
        _resultTableView.showsVerticalScrollIndicator = NO;
        [_resultTableView registerNib:[UINib nibWithNibName:NSStringFromClass([ResultTableViewCell class]) bundle:nil] forCellReuseIdentifier:kResultTableViewCell];
        _resultTableView.tableFooterView = [UIView new];
    }
    return _resultTableView;
}

- (UILabel *)tipLabel{
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, _tableView.frame.size.width, 40)];
    label.center = CGPointMake(_tableView.center.x, _tableView.center.y + 40);
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor grayColor];
    label.font = DefaultSystemFont(20);
    return label;
}

- (void)setTipLabelText:(NSArray*)players{
    NSMutableString *tmp = [NSMutableString new];
    [tmp appendString:@"进入房间的玩家："];
    for (PlayerModel *pm in players) {
        [tmp appendString:pm.playerName];
        [tmp appendString:@"  "];
    }
    _tipLabel.text = tmp;
    if (players.count >= 4) {
        _tipLabel.hidden = YES;
    }else{
        _tipLabel.hidden = NO;
    }
}

- (void)resetSelectedData{
    if (!_isEditAction) {
        _selectedBtn = nil;
        _selectedActionName = @"";
    }
    
    [_selectedAttributeNameArr removeAllObjects];
    [_selectedTargetPlayerArr removeAllObjects];
    
    [_controlTableView reloadData];
    [_collectionView reloadData];
}

- (void)setButtonStatus:(UIButton*)btn selected:(BOOL)flag{
    if (flag) {
        btn.layer.borderColor = [UIColor redColor].CGColor;
        [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        btn.layer.borderWidth = .5f;
    }else{
        btn.layer.borderColor = [UIColor grayColor].CGColor;
        [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        btn.layer.borderWidth = .5f;
    }
}

- (void)detailActionResult{
    //获取与自己相关的action
    _resultActionArr = [NSMutableArray new];
    [_resultActionArr addObjectsFromArray:_currentGameModel.actionArr];
    for (ActionModel *am in _currentGameModel.actionArr) {
        BOOL flag = NO;
        if ([am.owner.playerId isEqualToString:_owner.playerId]) {
            flag = YES;
        }
        for (PlayerModel *pm in am.targetsArr) {
            if ([pm.playerId isEqualToString:_owner.playerId]) {
                flag = YES;
                break;
            }
        }
        for (PlayerModel *pm in am.caguaArr) {//擦挂
            if ([pm.playerId isEqualToString:_owner.playerId]) {
                flag = YES;
                break;
            }
        }
        if ([am.transferedTo.playerId isEqualToString:_owner.playerId]) {//转雨
            flag = YES;
        }
        if (!flag) {
            [_resultActionArr removeObject:am];
        }
    }
    
    UIView *cv = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _scrollViewW, _scrollViewH)];
    //titleLabel
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, _scrollViewW, 60)];
    label.textAlignment = NSTextAlignmentCenter;
    NSInteger score = 0;
    for (ResultModel *rm in _currentGameModel.resultArr) {
        if ([rm.playerModel.playerId isEqualToString:_owner.playerId]) {
            score = rm.score;
            break;
        }
    }
    NSString *scoreStr = score>0?NSStringFormat(@"本局当前输赢: %ld",score):NSStringFormat(@"本局当前输赢: %ld",score);
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc]initWithString:scoreStr];
    UIColor *tmpColor = score>0?[UIColor redColor]:UIColorHex(#8BB335);
    if (score == 0) {
        tmpColor = [UIColor grayColor];
    }
    [attrStr addAttribute:NSForegroundColorAttributeName value:tmpColor range:NSMakeRange(8, scoreStr.length - 8)];
    [attrStr addAttribute:NSForegroundColorAttributeName value:tmpColor range:NSMakeRange(8, scoreStr.length - 8)];
    label.attributedText = attrStr;
    label.font = [UIFont boldSystemFontOfSize:25];
    label.backgroundColor = [UIColor whiteColor];
    [cv addSubview:label];
    //resultTableView
    [cv addSubview:self.resultTableView];
    //sureBtn
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, _scrollViewH - 100, _scrollViewW, 100)];
    view.backgroundColor = [UIColor whiteColor];
    ControlButton *sureBtn = [[ControlButton alloc]initWithTitle:@"确 定" fontSize:20 bgColor:UIColorHex(#EE8222)];
    sureBtn.layer.cornerRadius = 10.f;
    sureBtn.frame = CGRectMake((_scrollViewW - 300)/2, 10, 300, 80);
    [sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [sureBtn addTapBlock:^(UIButton *btn) {
        [[HWPopTool sharedInstance] closeWithBlcok:^{}];
    }];
    [view addSubview:sureBtn];
    [cv addSubview:view];
    
    [_resultTableView reloadData];
    [self showModalWithView:cv];
}

#pragma mark - 弹框
- (void)showModalWithView:(UIView*)view{
    view.layer.cornerRadius = 10.f;
    view.layer.masksToBounds = YES;
    [HWPopTool sharedInstance].shadeBackgroundType = ShadeBackgroundTypeGradient;
    [HWPopTool sharedInstance].closeButtonType = ButtonPositionTypeRight;
    [[HWPopTool sharedInstance] showWithPresentView:view animated:NO];
}

#pragma mark - Timer
- (void)createTimer{
    NSTimeInterval period = 5.0;//设置时间间隔
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer, DISPATCH_TIME_NOW, period * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(_timer, ^{
        [[WebSocketUtil sharedInstance]send:@"ping" things:@[@"pingTestStr"]];
        Log(@"------------------------------------");
    });
    dispatch_resume(_timer);
}

- (void)cancelTimer{
    dispatch_source_cancel(_timer);//取消定时器
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
